#include "UICircularProgressBar.h"

UICircularProgressBar::UICircularProgressBar()
{
	Position = Point{ 120, 120 };
}

UICircularProgressBar::UICircularProgressBar(float xPos, float yPos) : UIElement(xPos, yPos)
{
	this->m_ArcEndPointX = xPos;
	this->m_ArcEndPointY = yPos - Radius;
}

UICircularProgressBar::UICircularProgressBar(float xPos, float yPos, float radius) : UIElement(xPos, yPos, radius, radius)
{
	this->Radius = radius;
	this->m_ArcEndPointX = xPos;
	this->m_ArcEndPointY = yPos - Radius;
}

UICircularProgressBar::UICircularProgressBar(float xPos, float yPos, float radius, float stroke) : UIElement(xPos, yPos, radius, radius)
{
	this->Radius = radius;
	this->Stroke = stroke;
	this->m_ArcEndPointX = xPos;
	this->m_ArcEndPointY = yPos - Radius;
}

void UICircularProgressBar::UpdateArcEndPoint()
{
	if (this->Value > this->MaxValue)
	{
		this->Value = this->MaxValue;
		return;
	}
	else if (this->Value < this->MinValue)
	{
		this->Value = this->MinValue;
		return;
	}

	float valueRange = MaxValue - MinValue;
	float currentPercent = (Value - MinValue) / valueRange;
	if (currentPercent < 0.5f)
	{
		m_ArcSize = D2D1_ARC_SIZE_SMALL;
	}
	else
	{
		m_ArcSize = D2D1_ARC_SIZE_LARGE;
	}

	float angle = 2 * 3.14f * currentPercent;

	float xCoord = Position.x + sinf(angle) * Radius;
	float yCoord = Position.y - cosf(angle) * Radius;

	SetArcEndPoint(xCoord, yCoord);
}

void __stdcall UICircularProgressBar::Draw(Graphics* graphics)
{
	if (Value > MaxValue) Value = MaxValue;
	if (Value < MinValue) Value = MinValue;
	float CurrentValue = Value;
	CurrentValue = roundf(CurrentValue / Interval) * Interval;

	UpdateArcEndPoint();

	if (Value != m_PreviousValue)
		for (progress_callback_function cb : m_ProgressCallbacks)
			cb(this);

	m_PreviousValue = GetRoundedValue();

	// Drawing the circle
	graphics->DrawCircle(Position.x, Position.y, Radius, color.r, color.g, color.b, color.a, Stroke, false);

	// Drawing the progress arc
	if (Value > MinValue)
	{
		graphics->DrawArc(Position.x, Position.y - Radius, m_ArcEndPointX, m_ArcEndPointY, Radius,
			D2D1_SWEEP_DIRECTION_CLOCKWISE, m_ArcSize, ProgressColor.r, ProgressColor.g, ProgressColor.b, ProgressColor.a, Stroke);
	}
}
